/*
* @Author: xiaobing00008
* @Date:   2018-10-02 10:54:36
* @Last Modified by:   xiaobing00008
* @Last Modified time: 2018-10-03 19:26:00
*/
import React,{ Component,Fragment } from 'react'
import "antd/dist/antd.css";
import { Input, Button, List } from 'antd'
import store from './store'
import { getInputChangeAction, getAddItemAction, getDeleteItemAction} from './store/actionCreators'


class TodoList extends Component {
    constructor(props) {
        super(props)
        this.state = store.getState()
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleStoreChange = this.handleStoreChange.bind(this)
        this.handleBtnClick = this.handleBtnClick.bind(this)
        //组件订阅store，只要store发生变化，函数就自动被执行
        store.subscribe(this.handleStoreChange)
    }
    
    render() {
        return (
            <Fragment>
                <div style={{marginTop:'10px',marginLeft:'10px'}}>
                    <Input
                        value = {this.state.inputValue} 
                        placeholder="todolist info" 
                        style={{width:'300px',marginRight:'30px'}}
                        onChange = {this.handleInputChange} 
                    />
                    <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
                </div>
                <List
                  style={{width:'300px',marginTop:'10px',marginLeft:'10px'}}
                  bordered
                  dataSource={this.state.list}
                  renderItem={(item,index) => (
                    <List.Item onClick = {this.handleItemDelete.bind(this,index)}>{item}
                    </List.Item>)}
                />
            </Fragment>
        )
    }

    handleInputChange(e) {
        const action = getInputChangeAction(e.target.value)
        //click事件，数据变化，发送命令给store，store自动去reducer查找变化
        store.dispatch(action)
    }

    handleStoreChange() {
        //store发生变化，组件更新状态
        this.setState(store.getState())
    }

    handleBtnClick() {
        const action = getAddItemAction()
        //click事件，数据变化，发送命令给store，store自动去reducer查找变化
        store.dispatch(action)
    }

    handleItemDelete(index) {
        const action = getDeleteItemAction(index)
        //click事件，数据变化，发送命令给store，store自动去reducer查找变化
        store.dispatch(action)
    }
}

export default TodoList